package com.hepinghospital.user.ui.activity.eyecheck;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyFamilyActivity;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.BaseJsonResponse;
import com.rest.response.BaseListResponse;
import com.rest.response.MyFamilyListResponse;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import jz.joyoung.robot.util.TimeUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilList;
import jz.joyoung.robot.util.UtilString;

/**
 * Created by Administrator on 2018/6/11.
 */

public class EyeBookActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_eye_hospital_name)
    TextView tvEyeHospitalName;
    @BindView(R.id.ll_eye_hospital)
    LinearLayout rlEyeHospital;
    @BindView(R.id.tv_eye_left)
    TextView tvEyeLeft;
    @BindView(R.id.rl_eye_left)
    RelativeLayout rlEyeLeft;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.rl_patient_name)
    RelativeLayout rlPatientName;
    @BindView(R.id.rv_eye_type)
    RecyclerView rvEyeType;
    @BindView(R.id.tv_look_time)
    TextView tvLookTime;
    @BindView(R.id.rl_eye_time)
    RelativeLayout rlEyeTime;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_project)
    TextView tvProject;

    List<String> optionsItems = new ArrayList<String>();
    List<String> listCode = new ArrayList<>();
    List<BaseListResponse.checkLists> checkLists = new ArrayList<>();
    private EyeHospitalItemAdapter mEyeHospitalItemAdapter;
    boolean isContain = false;
    String hosDevId = "", applyHosid = "", applyHosname, applyPatid, source = "1", applyCheckTime;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_eye_book;
    }


    @Override
    protected void initData() {
        String hosDevIdIntent = getIntent().getStringExtra("hosDevId");
        if (!UtilString.isEmpty(hosDevIdIntent)) {
            //扫码进入
            hosDevId = hosDevIdIntent;
            source = "0";
            tvLookTime.setText(TimeUtil.getSystemTime());
            getEyeHospitalList();
        }
        optionsItems.add("左眼");
        optionsItems.add("右眼");
        optionsItems.add("双眼");

    }

    @Override
    protected void initViews() {
        tvTitle.setText("预约检查单");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvEyeType.setLayoutManager(manager);
        mEyeHospitalItemAdapter = new EyeHospitalItemAdapter(mContext, checkLists);
        rvEyeType.setAdapter(mEyeHospitalItemAdapter);
    }


    @OnClick({R.id.ll_eye_hospital, R.id.rl_eye_left, R.id.rl_patient_name, R.id.rl_eye_time, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_eye_hospital:
                startActivityForResult(EyeHospitalActivity.class, UIConstants.ENTERPRISE_HEAD_SYS);
                break;
            case R.id.rl_eye_left:
                initOptionPicker();
                break;
            case R.id.rl_patient_name:
                startActivityForResult(MyFamilyActivity.class, UIConstants.ENTERPRISE_HEAD_SELF);
                break;
            case R.id.rl_eye_time:
                initTimePicker();
                break;
            case R.id.tv_submit:
                submitEyeBook();
                break;
        }
    }


    /**
     * 医院列表
     *
     * @time 2021/1/6 15:22
     */
    private void getEyeHospitalList() {
        RestProxy.getInstance().getEyeHospitalList(hosDevId, "", new BaseObserver<List<BaseListResponse>>() {
            @Override
            public void onSuccess(List<BaseListResponse> result) {
                try {
                    List<BaseListResponse> data = result;
                    if (!UtilList.isEmpty(data)) {
                        tvEyeHospitalName.setText(data.get(0).hosName);
                        applyHosid = data.get(0).hosId;
                        Log.e("检查项目集合---", data.get(0).checkLists + "");
                        checkLists.clear();
                        checkLists.addAll(data.get(0).checkLists);
                        mEyeHospitalItemAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }
        });
    }


    class EyeHospitalItemAdapter extends RecyclerView.Adapter<EyeHospitalItemAdapter.ViewHolder> {

        Context mContext;
        List<BaseListResponse.checkLists> mCheckLists;


        EyeHospitalItemAdapter(Context context, List<BaseListResponse.checkLists> checkLists) {
            this.mContext = context;
            this.mCheckLists = checkLists;
        }

        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            ViewHolder myHolder;
            myHolder = new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_hospital_item, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            holder.tvEyeItemName.setText(mCheckLists.get(position).name);
            holder.itemView.setOnClickListener(v -> {
                if (listCode.size() > 0) {
                    for (int i = 0; i < listCode.size(); i++) {
                        if (listCode.get(i).equals(mCheckLists.get(position).code)) {
                            isContain = true;
                        }
                    }
                    if (isContain) {
                        //之前选中过
                        listCode.remove(mCheckLists.get(position).code);
                        holder.ivEyeItemCheck.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.check));
                    } else {
                        listCode.add(mCheckLists.get(position).code);
                        holder.ivEyeItemCheck.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.check_focus));
                    }
                    isContain = false;
                    Log.e("擅长list---", listCode.size() + "");
                } else {
                    listCode.add(mCheckLists.get(position).code);
                    holder.ivEyeItemCheck.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.check_focus));
                }

            });
        }

        @Override
        public int getItemCount() {
            return mCheckLists.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_eye_item_name)
            TextView tvEyeItemName;
            @BindView(R.id.iv_eye_item_check)
            ImageView ivEyeItemCheck;

            ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }


    private void submitEyeBook() {
        if (UtilString.isEmpty(tvEyeHospitalName.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请选择检查医院");
            return;
        }
        if (UtilString.isEmpty(tvPatientName.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请选择就诊人");
            return;
        }
        if (listCode.size() <= 0) {
            ToastUtil.showToast(mContext, "请至少选择一项检查项目");
            return;
        }
        if (UtilString.isEmpty(tvLookTime.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请选择检查时间");
            return;
        }

        Log.e("字符串---", UtilString.listToString(listCode));
        RequestBody requestBody = new FormBody.Builder()
                .add("checkList", UtilString.listToString(listCode))
                .add("checkSeries", tvEyeLeft.getText().toString().trim())
                .add("hosDevId", hosDevId) //设备编号
                .add("applyHosid", applyHosid)
                .add("applyHosname", tvEyeHospitalName.getText().toString().trim())
                .add("applyPatid", applyPatid)//申请患者id
                .add("applyCheckTime", tvLookTime.getText().toString().trim())
                .add("source", source) //申请来源（扫码、预约） 0扫码、1预约
                .build();
        RestProxy.getInstance().createCheck(requestBody, new Observer<BaseJsonResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseJsonResponse baseJsonResponse) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("createCheck", baseJsonResponse);
                    startActivity(EyeBookResultActivity.class, bundle);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case UIConstants.ENTERPRISE_HEAD_SYS:
                if (data != null) {
                    BaseListResponse eyeHospital = (BaseListResponse) data.getSerializableExtra("eyeHospital");
                    assert eyeHospital != null;
                    tvEyeHospitalName.setText(eyeHospital.hosName);
                    applyHosid = eyeHospital.hosId;
                    Log.e("检查项目---", eyeHospital.checkLists.size() + "");
                    checkLists.clear();
                    checkLists.addAll(eyeHospital.checkLists);
                    mEyeHospitalItemAdapter.notifyDataSetChanged();
                }
                break;
            case UIConstants.ENTERPRISE_HEAD_SELF:
                if (data != null) {
                    MyFamilyListResponse myFamily = (MyFamilyListResponse) data.getSerializableExtra(UIConstants.OBJ_MyFamilyListResponse);
                    assert myFamily != null;
                    tvPatientName.setText(myFamily.name);
                    applyPatid = myFamily.patientId;
//                    BaseApplication.currentFamilyId = myFamily.patientId;
                }
                break;
        }
    }

    /**
     * 初始化左右眼条件选择器
     *
     * @time 2021/1/5 14:53
     */
    private void initOptionPicker() {

        //返回的分别是三个级别的选中位置
        //LinkedHashMap 有序
        OptionsPickerView pvCustomOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //LinkedHashMap 有序
                String tx = optionsItems.get(options1);
                if (!UtilString.isEmpty(tx)) {
                    tvEyeLeft.setText(tx);

                }

            }
        }).build();


        pvCustomOptions.setNPicker(optionsItems, null, null);
        pvCustomOptions.show();
    }

    /**
     * 时间选择器
     *
     * @time 2021/1/7 9:27
     */
    private void initTimePicker() {//Dialog 模式下，在底部弹出
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(year, month, day);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2031, 0, 1);

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> tvLookTime.setText(getTime(date)))
                .setTimeSelectChangeListener(date -> Log.i("pvTime", "onTimeSelectChanged"))
                .setDate(selectedDate)
                .setRangDate(calendar, endDate)
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(view -> Log.i("pvTime", "onCancelClickListener"))
                .setLineSpacingMultiplier(2.0f)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }
}
